#pragma once

#include "strategy/optimized_strategy_base.h"
#include "utils/optimized_price_history.h"
#include "utils/memory_pool.h"
#include "utils/simd_math.h"
#include "utils/simd_math_ext.h"
#include <memory>
#include <string>
#include <atomic>

namespace hft {

/**
 * @brief 优化的均值回归策略
 * 
 * 这个策略基于价格偏离移动平均线的程度来交易。
 * 它利用SIMD指令集优化、内存池和优化的历史数据管理来提高性能。
 */
class OptimizedMeanReversionStrategy : public OptimizedStrategyBase {
public:
    /**
     * @brief 构造函数
     * @param symbol 交易品种
     * @param window_size 移动平均窗口大小
     * @param entry_threshold 入场阈值（标准差倍数）
     * @param exit_threshold 出场阈值（标准差倍数）
     */
    OptimizedMeanReversionStrategy(
        const std::string& symbol,
        size_t window_size = 20,
        double entry_threshold = 2.0,
        double exit_threshold = 0.5)
        : OptimizedStrategyBase("OptimizedMeanReversion_" + symbol)
        , symbol_(symbol)
        , window_size_(window_size)
        , entry_threshold_(entry_threshold)
        , exit_threshold_(exit_threshold)
        , position_(0)
        , is_trading_(false)
        , last_trade_time_(0)
        , min_trade_interval_(1000)  // 最小交易间隔（毫秒）
    {
    }

    /**
     * @brief 启动策略
     */
    void start() override {
        is_trading_ = true;
        LOG(INFO) << "启动优化的均值回归策略: " << getName();
    }

    /**
     * @brief 停止策略
     */
    void stop() override {
        is_trading_ = false;
        LOG(INFO) << "停止优化的均值回归策略: " << getName();
    }

    /**
     * @brief 处理市场数据
     * @param data 市场数据
     */
    void processMarketData(const MarketData& data) override {
        if (!is_trading_ || data.symbol != symbol_) return;

        try {
            // 获取价格历史
            auto price_history = getPriceHistory(symbol_);
            if (!price_history) {
                LOG(WARNING) << "未找到价格历史: " << symbol_;
                return;
            }

            // 确保有足够的数据
            if (price_history->getCount() < window_size_) {
                return;
            }

            // 计算移动平均
            double sma = price_history->calculateSMA(window_size_);
            
            // 计算标准差
            double std_dev = price_history->calculateStdDev(window_size_);
            
            // 获取最新价格
            double latest_price = price_history->getLatestPrice();
            
            // 计算Z-Score
            double z_score = (latest_price - sma) / std_dev;

            // 检查是否可以交易（考虑最小交易间隔）
            auto current_time = std::chrono::steady_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
                current_time.time_since_epoch()).count();

            if (elapsed - last_trade_time_ < min_trade_interval_) {
                return;
            }

            // 交易逻辑
            if (position_ == 0) {
                // 没有持仓，检查是否开仓
                if (z_score > entry_threshold_) {
                    // 价格高于均值，做空
                    openPosition(-1);
                    last_trade_time_ = elapsed;
                } else if (z_score < -entry_threshold_) {
                    // 价格低于均值，做多
                    openPosition(1);
                    last_trade_time_ = elapsed;
                }
            } else {
                // 有持仓，检查是否平仓
                if ((position_ > 0 && z_score > -exit_threshold_) ||
                    (position_ < 0 && z_score < exit_threshold_)) {
                    closePosition();
                    last_trade_time_ = elapsed;
                }
            }

            // 记录指标
            LOG(INFO) << "策略指标 " << getName() << ":"
                      << " 价格=" << latest_price
                      << " SMA=" << sma
                      << " 标准差=" << std_dev
                      << " Z-Score=" << z_score;

        } catch (const std::exception& e) {
            LOG(ERROR) << "处理市场数据时发生错误: " << e.what();
        }
    }

    /**
     * @brief 获取策略状态
     * @return 策略状态的JSON字符串
     */
    std::string getState() const override {
        nlohmann::json state = nlohmann::json::parse(OptimizedStrategyBase::getState());
        
        auto price_history = getPriceHistory(symbol_);
        if (price_history && price_history->getCount() >= window_size_) {
            double latest_price = price_history->getLatestPrice();
            double sma = price_history->calculateSMA(window_size_);
            double std_dev = price_history->calculateStdDev(window_size_);
            double z_score = (latest_price - sma) / std_dev;
            
            state["symbol"] = symbol_;
            state["position"] = position_;
            state["window_size"] = window_size_;
            state["entry_threshold"] = entry_threshold_;
            state["exit_threshold"] = exit_threshold_;
            state["is_trading"] = is_trading_;
            state["latest_price"] = latest_price;
            state["sma"] = sma;
            state["std_dev"] = std_dev;
            state["z_score"] = z_score;
        }
        
        return state.dump(4);
    }

private:
    /**
     * @brief 开仓
     * @param direction 方向（1表示做多，-1表示做空）
     */
    void openPosition(int direction) {
        // 创建订单
        Order* order = createOrder(
            symbol_,
            (direction > 0) ? OrderDirection::BUY : OrderDirection::SELL,
            OrderType::MARKET,
            1.0  // 简化示例，实际应该根据资金管理计算数量
        );

        // 发送订单
        if (trading_system_) {
            trading_system_->processOrder(*order);
        }

        // 释放订单对象
        releaseOrder(order);

        // 更新持仓
        position_ = direction;

        LOG(INFO) << "开仓 " << getName() << ": " 
                  << (direction > 0 ? "做多" : "做空");
    }

    /**
     * @brief 平仓
     */
    void closePosition() {
        if (position_ == 0) return;

        // 创建订单
        Order* order = createOrder(
            symbol_,
            (position_ > 0) ? OrderDirection::SELL : OrderDirection::BUY,
            OrderType::MARKET,
            1.0  // 简化示例，实际应该根据持仓量设置
        );

        // 发送订单
        if (trading_system_) {
            trading_system_->processOrder(*order);
        }

        // 释放订单对象
        releaseOrder(order);

        // 更新持仓
        position_ = 0;

        LOG(INFO) << "平仓 " << getName();
    }

private:
    std::string symbol_;                // 交易品种
    size_t window_size_;                // 移动平均窗口大小
    double entry_threshold_;            // 入场阈值
    double exit_threshold_;             // 出场阈值
    std::atomic<int> position_;         // 持仓方向（1=多头，-1=空头，0=无持仓）
    std::atomic<bool> is_trading_;      // 是否正在交易
    std::atomic<int64_t> last_trade_time_; // 上次交易时间
    int64_t min_trade_interval_;        // 最小交易间隔（毫秒）
};

} // namespace hft